package com.wing.common.constant;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;


import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.*;

public class JaxbUtil {



    public static void main(String[] args) {
        JaxbUtil httpUtil = new JaxbUtil();
        Map<String, String> params = new HashMap<>();
        params.put("appid","OAAPPID2023");
        params.put("secret","KPHGKLwP97VCeqWlmwRGPVFI/1d690CICOxJPNcVL1S+xbe3lOxV7UUpsj8NjN4FOdjvjqxb7ksQvCD0woOE4j9UyBG7ZPwXKo5LAbJ0pVGvBu6qTgjWoQ/Bhd66JLNI+9C+tipEzJAHdMFPk3l5Et6Opo2ptUG+4IvScBducdezAFPu0I5fXO84rePfo3bZqXkXGy4K3t30Q8SeCKct+A8V+s/r81yJ2yDNUiEP9+v14Fb4vksuJQpgNddFMuGI41tq0vGZR0dvpplgytLK5BJkIpiZFfu9hTBgfU5FLSx90vpjx685MOEgJyNrlVQPukiJ4SWsxM8kAJRUepvYLg==");
        //String s = httpUtil.postData("http://tkoa.tkmold.com/api/ec/dev/auth/applytoken", params, params);
        Map<String, Object> stringObjectMap = testGetoken(null);
        System.out.println(stringObjectMap);
    }
    /**
     * 第二步：
     *
     * 通过第一步中注册系统返回信息进行获取token信息
     */
    public static Map<String,Object> testGetoken(String address){
        // 从系统缓存或者数据库中获取ECOLOGY系统公钥和Secret信息
        String spk ="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2wr29DmWxSYskMwtBgJoKwaLwOaciSezMdYsXQNjIwBrIi7v5v340L" +
                "pnxcEjN5MFH25fKCfUVf7V+mjCa9xtaumX0d0ZIi7YwJt5PFbTVJesp+gEn02St3aHXHDPan9fcHu17IwKmtRXwfZVUesWH6SItPp9enE6jl5" +
                "iKGPCkz88i7edVpjnXSbL/Die4fgqJYOCKT5zQqUuKLABL0mH4u69n1zF/DWKAKyWghn7KQk6qxw9+0nYm+VbTgRQqFbgV4+t87JwPB3t" +
                "B4pP3O8LxoDj+5TNgDhywHdJYQy3oNyUZeR12LIdhqTgoODFkV8V32S2P48rd9EwsN0YE6lkaQIDAQAB";
        String secret = "1aed1733-23f8-43fa-9817-5e992aedf92e";
        // 如果为空,说明还未进行注册,调用注册接口进行注册认证与数据更新
        /*if (Objects.isNull(secret)||Objects.isNull(spk)){
            //testRegist(address);
            // 重新获取最新ECOLOGY系统公钥和Secret信息
             spk ="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2wr29DmWxSYskMwtBgJoKwaLwOaciSezMdYsXQNjIwBrIi7v5v340L" +
                    "pnxcEjN5MFH25fKCfUVf7V+mjCa9xtaumX0d0ZIi7YwJt5PFbTVJesp+gEn02St3aHXHDPan9fcHu17IwKmtRXwfZVUesWH6SItPp9enE6jl5" +
                    "iKGPCkz88i7edVpjnXSbL/Die4fgqJYOCKT5zQqUuKLABL0mH4u69n1zF/DWKAKyWghn7KQk6qxw9+0nYm+VbTgRQqFbgV4+t87JwPB3t" +
                    "B4pP3O8LxoDj+5TNgDhywHdJYQy3oNyUZeR12LIdhqTgoODFkV8V32S2P48rd9EwsN0YE6lkaQIDAQAB";
             secret = "1aed1733-23f8-43fa-9817-5e992aedf92e";
        }*/
        // 公钥加密,所以RSA对象私钥为null
        RSA rsa = new RSA(null,spk);
        //对秘钥进行加密传输，防止篡改数据
        String encryptSecret = rsa.encryptBase64(secret, CharsetUtil.CHARSET_UTF_8, KeyType.PublicKey);
        //调用ECOLOGY系统接口进行注册
        String data = HttpRequest.post("http://tkoa.tkmold.com/api/ec/dev/auth/applytoken")
                .header("appid","OAAPPID2023")
                .header("secret",encryptSecret)
                .header("time","3600")
                .execute().body();
        System.out.println("testGetoken()："+data);
        Map<String,Object> datas = JSONUtil.parseObj(data);
        //ECOLOGY返回的token
        // TODO 为Token缓存设置过期时间
        return datas;
    }

    /**
     * 发起post请求
     * @param URL  请求地址
     * @param params  参数 格式为map
     * @param header 请求头，可以为null
     * @return
     */
    public String postData(String URL, Map<String, String> params, Map<String, String> header) {
        String respStr = null;
        //获取Http客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建post请求
        HttpPost httpPost = new HttpPost(URL);
        //存储参数的BasicNameValuePair集合
        ArrayList list = new ArrayList();

        if(params != null){
            //获得参数的迭代器
            Iterator iterator = params.entrySet().iterator();

            //迭代参数
            while(iterator.hasNext()) {
                Map.Entry entry = (Map.Entry)iterator.next();
                //BasicNameValuePair通常是用来封装post请求中的参数名称和值；
                list.add(new BasicNameValuePair((String)entry.getKey(), (String)entry.getValue()));
            }
        }

        //请求模型
        CloseableHttpResponse response = null;

        try {
            /*两个键值对，被UrlEncodedFormEntity实例编码后变为如下内容：
            param1=value1&param2=value2
            然后将请求参数放进Entity中*/
            httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
            //如果请求头不为null
            if (header != null) {
                Iterator headerIterator = header.entrySet().iterator();

                //就遍历请求头中的参数
                while(headerIterator.hasNext()) {
                    Map.Entry headerEntry = (Map.Entry)headerIterator.next();
                    httpPost.setHeader((String)headerEntry.getKey(), (String)headerEntry.getValue());
                }
            }

            //发送post请求
            response = httpClient.execute(httpPost);
            //如果请求不为空并且响应code为200
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                //获取请求模型返回的实体
                HttpEntity responseEntity = response.getEntity();
                respStr = this.entityToString(responseEntity);
            }

            String resultStr = respStr;
            return resultStr;
        } catch (UnsupportedEncodingException var23) {
            var23.printStackTrace();
        } catch (ClientProtocolException var24) {
            var24.printStackTrace();
        } catch (IOException var25) {
            var25.printStackTrace();
        } finally {
            try {
                httpClient.close();
                if (response != null) {
                    response.close();
                }
            } catch (IOException var22) {
                var22.printStackTrace();
            }

        }

        return null;
    }



    /**
     * 解析HttpEntity
     * @param entity
     * @return
     * @throws IOException
     */
    private String entityToString(HttpEntity entity) throws IOException {
        String result = null;
        InputStreamReader inputStreamReader = null;
        try {
            if (entity != null) {
                long contentLength = entity.getContentLength();
                if (contentLength != -1L && contentLength < 2048L) {
                    result = EntityUtils.toString(entity, "UTF-8");
                } else {
                    inputStreamReader = new InputStreamReader(entity.getContent(), "UTF-8");
                    CharArrayBuffer charArrayBuffer = new CharArrayBuffer(2048);
                    char[] chars = new char[1024];

                    int index;
                    while((index = inputStreamReader.read(chars)) != -1) {
                        charArrayBuffer.append(chars, 0, index);
                    }

                    result = charArrayBuffer.toString();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            inputStreamReader.close();
        }

        return result;
    }
}
